package com.vmove.childtrain.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串验证
 * @author guoxiaodong
 * @date 2014年11月26日
 * @time 下午4:28:17
 */
public class StringUtils {
	/**
	 * 缩略图
	 * @param bmp
	 * @param needRecycle
	 * @return
	 */
	
	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}
		
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

	/**
	 * 验证手机号
	 * @author guoxiaodong
	 * @date 2014年11月26日
	 * @time 下午4:28:02
	 * @param phone
	 * @return
	 */
	public static boolean isPhoneValid(String phone){
		if(TextUtils.isEmpty(phone)) {
			return false;
		}
		if(phone.length() != 11) {
			return false;
		}
		try {
		    Long.parseLong(phone);
		} catch(NumberFormatException e) {
			return false;
		}
		String prefix = phone.substring(0, 3);
		int prefixNum = Integer.parseInt(prefix);
		if(prefixNum < 130 || prefixNum >= 200) {
			return false;
		}
		return true;
	}
	
	/**
	 * 验证密码
	 * @author guoxiaodong
	 * @time 下午4:46:38
	 * @param password
	 * @return
	 */
	public static boolean isPasswordValid(String password){
		String passwordRegular = "A-Za-z0-9~!@#$%&_.";
		if(TextUtils.isEmpty(password)) {
			return false;
		}
		if(password.length() < 6 && password.length() > 12){
			return false;
		}
		if(Pattern.compile(passwordRegular).matcher(password).matches()){
			return false;
		}
		return true;
	}
	
	
	/**
	 * 验证真实姓名
	 * @param name
	 * @return
	 */
	public static boolean isRealName(String name){
		if(TextUtils.isEmpty(name)) {
			return false;
		}
		if(name.length() < 2 || name.length() > 8){
			return false;
		}
		return true;
	}
	
	/**
	 * 截取字符串（根据下标）
	 * @param str
	 * @param start
	 * @param end
	 * @param insteadStr
	 * @return
	 */
	public static String cutSubstring(String str, int start , int end, String insteadStr){
		if(str != null && !"".equals(str) && str.length() < end && str.length() > start){
			str = str.substring(start, end);
			str = str + insteadStr;
		}
		return str;
	}
	
	/**
	 * 生成随机数
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length){
	     String str= "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	     Random random=new Random();
	     StringBuffer sb=new StringBuffer();
	     for(int i=0;i<length;i++){
	       int number=random.nextInt(str.length());
	       sb.append(str.charAt(number));
	     }
	     return sb.toString();
	 }

	public static void main(String args[]){
		Sysout.sysout(System.currentTimeMillis());
	}
	
	/**
	 * 判断email格式是否正确
	 * @param email
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}
	/** 
	 * 获取随机字母数字组合 
	 * @param length  字符串长度 
	 * @return 
	 */  
	public static String getRandomCharAndNumr(Integer length) {
	    String str = "";
	    Random random = new Random();
	    for (int i = 0; i < length; i++) {  
	        boolean b = random.nextBoolean();  
	        if (b) { // 字符串  
	            int choice = random.nextBoolean() ? 65 : 97; //取得65大写字母还是97小写字母  
//	            str += (char) (65 + random.nextInt(26));// 取得大写字母  
	            str += (char) (choice + random.nextInt(26));
	        } else { // 数字  
	            str += String.valueOf(random.nextInt(10));
	        }  
	    }  
	    return str;  
	}  
	/** 
	 * 验证随机字母数字组合是否纯数字与纯字母 
	 *  
	 * @param str 
	 * @return true 是 ， false 否 
	 */  
	public static boolean isRandomUsable(String str) {
	    // String regExp =  
	    // "^[A-Za-z]+(([0-9]+[A-Za-z0-9]+)|([A-Za-z0-9]+[0-9]+))|[0-9]+(([A-Za-z]+[A-Za-z0-9]+)|([A-Za-z0-9]+[A-Za-z]+))$";  
	    String regExp = "^([0-9]+)|([A-Za-z]+)$";
	    Pattern pat = Pattern.compile(regExp);
	    Matcher mat = pat.matcher(str);
	    return mat.matches();  
	}  
	/**
	 * 去除字符串所有空格
	 * @param str
	 * @return
	 */
	public static String delSpace(String str){
		str = str.trim();//去除两边空格
		str = str.replace(" ", "");//去除中间空格
		return str;
	}
	
	 /**
	  * byte[]转16进制 string
	 * @param src
	 * @return
	 */
	public static String bytesToHexString(byte[] src)
	    {
	        StringBuilder stringBuilder = new StringBuilder("");
	        if (src == null || src.length<= 0){
	            return null;
	        }
	        for(int i = 0;i < src.length;i++){
	            int v = src[i] & 0xFF;
	            String hv = Integer.toHexString(v);
	            if(hv.length() < 2){
	                stringBuilder.append(0);
	            }
	            stringBuilder.append(hv);
	        }
	        return stringBuilder.toString();
	         
	    }
	
	 /** 
     * 将byte[]转为16进制字符串
     * @param bytes 
     * @return 
     */  
    public static String bytes2hex(byte[] bytes)
    {  
        final String HEX = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes)  
        {  
            // 取出这个字节的高4位，然后与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数  
            sb.append(HEX.charAt((b >> 4) & 0x0f));  
            // 取出这个字节的低位，与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数  
            sb.append(HEX.charAt(b & 0x0f));  
        }  
  
        return sb.toString();  
    }
	
	/**
	 * 读取流到byte数组
	 * @param inStream
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}
	
	 /**
	   * 把16进制字符串转换成字节数组
	   * @return byte[]
	   */
	  public static byte[] hexStringToByte(String hex) {
	   int len = (hex.length() / 2);
	   byte[] result = new byte[len];
	   char[] achar = hex.toCharArray();
	   for (int i = 0; i < len; i++) {
	    int pos = i * 2;
	    result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
	   }
	   return result;
	  }
	 
	 private static int toByte(char c) {
	    byte b = (byte) "0123456789abcdef".indexOf(c);
	    return b;
	 }
}

